import { postGetallsubjects, postQuickschools } from "@/apis/endpoint/home";
import { EnumEducation, EnumEducationType, MemberResumeEducationExpRequest } from "@/apis/endpoint/model";
import { postMyAddorediteducationexp } from "@/apis/endpoint/my";
import GpContainer from "@/components/GpContainer";
import GpFontIcon from "@/components/GpFontIcon";
import GpVerticelLine from "@/components/GpVerticelLine";
import { pageMapper } from "@/constants/pageMap";
import { useNavigateEventChannel } from "@/hooks/useNavigateEventChannel";
import { withCache } from "@/utils/cache";
import { dateFormat, dateUtil } from "@/utils/date";
import { isSetValue } from "@/utils/helper";
import { navigate } from "@/utils/navigation";
import { DatetimePicker, Picker, Popup, Switch } from "@taroify/core";
import { Button, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import clsx from "clsx";
import { useEffect, useState } from "react";
import { useImmer } from "use-immer";
import { educationMap, educationOptions } from "../../enum-options";

interface State {
  id?: number
  schoolName?: string
  education?: EnumEducation
  subjectId?: number
  professionName?: string
  educationType?: EnumEducationType
  content?: string
}

interface EducationExp extends State {
  startAt?: string
  endAt?: string
}

export default function Index() {
  const [loading, setLoading] = useState(false)
  const [state, setState] = useImmer<State>({
    educationType: EnumEducationType.非全日制
  })
  const [openTime, setOpenTime] = useState(false)
  const [minWorkDate] = useState(new Date(2000, 0, 1))
  const [maxWorkDate] = useState(new Date())
  const [workAction, setWorkAction] = useState<"start"|"end"|"pending">("pending")
  const [workStartAt, setWorkStartAt] = useState<Date>()
  const [workEndAt, setWorkEndAt] = useState<Date>()
  const [openEducation, setOpenEducation] = useState(false)
  const { eventChannel } = useNavigateEventChannel()
  useEffect(() => {
    if (eventChannel) {
      eventChannel.once("getEducation", (exp: EducationExp) => {
        if (exp) {
          const { startAt, endAt, ...s } = exp
          if (startAt) setWorkStartAt(dateUtil(startAt).toDate())
          if (endAt) setWorkEndAt(dateUtil(endAt).toDate())
          setState({...state, ...s})
        }
      })
    }
  }, [])
  function triggerWorkAction(action: "start" | "end") {
    setWorkAction(action)
    setOpenTime(true)
  }
  function confirmWorkAction(date: Date) {
    workAction === "start" ? setWorkStartAt(date) : setWorkEndAt(date)
    setOpenTime(false)
    setWorkAction("pending")
  }
  function handleEditSchoolName() {
    navigate(pageMapper.fieldEdit.search, null, "navigateTo", {
      events: {
        receiveField({ label }: IOption<any>) {
          setState(draft => {
            draft.schoolName = label
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          maxContent: 40,
          navigationbarTitleText: "学校名称",
          placeholder: "请输入学校名称",
          searchAction(value) {
            return postQuickschools({
              top: 20,
              keywords: value
            }).send({ showLoading: false })
          },
          content: state.schoolName
        } as FieldEditStateSearch)
      },
    })
  }
  function handleEditSubject() {
    navigate(pageMapper.fieldEdit.search, null, "navigateTo", {
      events: {
        receiveField({ label, value }: IOption<any>) {
          setState(draft => {
            draft.subjectId = value
            draft.professionName = label
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          maxContent: 40,
          navigationbarTitleText: "专业名称",
          placeholder: "请输入专业名称",
          searchAction(value) {
            return withCache("postGetallsubjects", () => postGetallsubjects().send({ showLoading: false }))
            .then<IOption<number>[]>(list => {
              return list.filter(l => l.level === 3 && l.name.match(value)).map(({id, name}) => ({value: id, label: name}))
            })
          },
          content: state.professionName,
          contentId: state.subjectId
        } as FieldEditStateSearch)
      },
    })
  }
  function handleEditContent() {
    navigate(pageMapper.fieldEdit.multiline, null, "navigateTo", {
      events: {
        receiveField(value: string) {
          setState(draft => {
            draft.content = value
          })
        }
      },
      success(res) {
        res.eventChannel.emit("getField", {
          content: state.content,
          description: "简述您的在校经历，向HR展示您的个人特点",
          filedName: "在校经历",
          placeholder: "1.在校担任职务\n2.获得荣誉\n3.所学主要课程",
        } as FieldEditState)
      },
    })
  }
  async function handleSave() {
    if (!state.schoolName) {
      Taro.showToast({
        title: "请输入学校名称",
        icon: "none"
      })
      return
    }
    if (!isSetValue(state.education)) {
      Taro.showToast({
        title: "请选择学历",
        icon: "none"
      })
      return
    }
    if (!isSetValue(state.professionName)) {
      Taro.showToast({
        title: "请输入专业名称",
        icon: "none"
      })
      return
    }
    if (!workStartAt) {
      Taro.showToast({
        title: "请选择开始时间",
        icon: "none"
      })
      return
    }
    if (!workEndAt) {
      Taro.showToast({
        title: "请选择结束时间",
        icon: "none"
      })
      return
    }
    if (!state.content) {
      Taro.showToast({
        title: "请输入在校经历",
        icon: "none"
      })
      return
    }
    const params: MemberResumeEducationExpRequest = {
      startTime: dateFormat(workStartAt, "short"),
      endTime: dateFormat(workEndAt, "short"),
      id: state.id,
      education: state.education,
      educationType: state.educationType!,
      schoolName: state.schoolName,
      content: state.content,
      professionName: state.professionName,
      subjectId: state.subjectId
    }
    try {
      setLoading(true)
      await postMyAddorediteducationexp(params).send()
      Taro.showToast({
        title: (params.id ? "修改" : "新增") + "成功",
        icon: "success"
      })
      navigate()
    } catch (error) {
      setLoading(false)
    }
  }
  function renderActionPannels() {
    return (
      <View>
        { renderWorkRange() }
        { renderEducation() }
      </View>
    )
  }
  function renderWorkRange() {
    return (
      <Popup open={openTime} rounded placement="bottom" onClose={setOpenTime}>
        <Popup.Backdrop />
        <DatetimePicker
          type="year-month"
          min={minWorkDate}
          max={maxWorkDate}
          defaultValue={workAction === "start" ? workStartAt : workEndAt}
          key={workAction}
          onConfirm={confirmWorkAction}
        >
          <DatetimePicker.Toolbar>
            <DatetimePicker.Button type="cancel">取消</DatetimePicker.Button>
            <DatetimePicker.Title>{workAction === "start" ? "开始时间" : "结束时间"}</DatetimePicker.Title>
            <DatetimePicker.Button type="confirm">确认</DatetimePicker.Button>
          </DatetimePicker.Toolbar>
        </DatetimePicker>
      </Popup>
    )
  }
  function renderEducation() {
    const defaultValue = isSetValue(state.education) ? [state.education] : void 0
    return (
      <Popup open={openEducation} rounded placement="bottom" onClose={setOpenEducation}>
        <Popup.Backdrop />
        <Picker
          title="学历"
          columns={educationOptions}
          defaultValue={defaultValue}
          key={state.education}
          onCancel={() => setOpenEducation(false)}
          onConfirm={([value]: EnumEducation[]) => setState(draft => {draft.education = value; setOpenEducation(false);})}
        ></Picker>
      </Popup>
    )
  }
  return (
    <GpContainer className="bg-white">
      <View className="px-[32px] box-border pt-[16px]">
        <View className="text-[48px] font-bold text-primary">教育背景</View>
      </View>
      <View className="px-[32px] pb-[48px]">
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">学校名称</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditSchoolName}>
            <View className={clsx("text-[32px] truncate", state.schoolName ? "text-primary font-bold" : "text-placeholder")}>
              {state.schoolName || "请输入学校名称"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">学历</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={() => setOpenEducation(true)}>
            <View className={clsx("text-[32px] truncate", state.education ? "text-primary font-bold" : "text-placeholder")}>
              {isSetValue(state.education) ? educationMap.get(state.education) : "请选择"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">专业</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditSubject}>
            <View className={clsx("text-[32px] truncate", state.subjectId ? "text-primary font-bold" : "text-placeholder")}>
              {state.professionName || "请输入专业名称"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">时间</View>
          <View className="flex flex-row justify-between items-center gap-[24px] mt-[32px]">
            <View onClick={() => triggerWorkAction('start')} className={clsx("text-[32px] flex-1", workStartAt ? "text-primary font-bold" : "text-placeholder")}>
              {workStartAt ? dateFormat(workStartAt, "YYYY/MM") : "开始时间"}
            </View>
            <GpVerticelLine width={20} height={2} color="#313337" />
            <View onClick={() => triggerWorkAction('end')} className={clsx("text-[32px] flex-1", workEndAt ? "text-primary font-bold" : "text-placeholder")}>
              {workEndAt ? dateFormat(workEndAt, "YYYY/MM") : "结束时间"}
            </View>
          </View>
        </View>
        <View className="py-[48px] border-b-2 border-solid border-b-[#EEEEEE] flex flex-row items-center justify-between">
          <View className="text-[32px] text-primary">统招</View>
          <Switch checked={state.educationType === EnumEducationType.全日制} onChange={value => setState(draft => {
            draft.educationType = value ? EnumEducationType.全日制 : EnumEducationType.非全日制
          })} size={20} />
        </View>
        <View className="pt-[48px] pb-[32px] border-b-2 border-solid border-b-[#EEEEEE]">
          <View className="text-[28px] text-primary">在校经历</View>
          <View className="flex flex-row justify-between mt-[32px]" onClick={handleEditContent}>
            <View className={clsx("text-[32px] truncate", state.content ? "text-primary font-bold" : "text-placeholder")}>
              {state.content || "填选 请输入"}
            </View>
            <GpFontIcon name="icon-a-jiantou_youda" size={40} className="text-placeholder flex-none" />
          </View>
        </View>
      </View>
      <View className="px-[32px] py-[48px]">
        <Button className="h-[80px] mt-[80px] rounded-[64px] bg-theme text-white flex flex-row justify-center items-center text-[32px]" loading={loading} onClick={handleSave}>
          保存
        </Button>
      </View>
      { renderActionPannels() }
    </GpContainer>
  )
}
